const { queryAll } = require('../../database/dbUtils')
import  fs from 'fs'
import path from 'path'
import {v1} from 'uuid'
import fse = require("fs-extra");
//上传文件的目录地址
const UPLOAD_DIR = path.join(__dirname, "../../../public/upload");
export const getLogin = async (ctx: any) => {
  let { loginName, loginPass } = ctx.request.query;
  const sql = "select * from userlist";
  let data: any = await queryAll(sql);
  let obj = data.find((item: any) => {
    return item.user == loginName;
  });

  if (obj) {
    if (obj.pass == loginPass) {
      ctx.body = {
        code: "01",
        msg: "登陆成功",
        obj,
      };
    } else {
      ctx.body = {
        code: "02",
        msg: "密码错误",
      };
    }
  } else {
    ctx.body = {
      code: "03",
      msg: "账号错误",
    };
  }
};
export const getscblist = async (ctx: any) => {
  let { page, pageIndex, val1 = '', val2 = '', val3 = '', val4 = '', val5 = '', val6 = '', } = ctx.request.query


  const sql = 'select * from scb';
  let data: any = await queryAll(sql)
  if (val1 != '') {
    data = data.filter((item: any) => {
      return item.name.indexOf(val1) != -1
    })
  }
  if (val2 != '') {
    data = data.filter((item: any) => {
      return item.qwstage == val2
    })
  }
  if (val3 != '') {
    data = data.filter((item: any) => {
      return item.scb == val3
    })
  }
  if (val4 != '') {
    data = data.filter((item: any) => {
      return item.stage == val4
    })
  }
  if (val5 != '') {
    data = data.filter((item: any) => {
      return item.sex == val5
    })
  }
  if (val6 != '') {
    data = data.filter((item: any) => {
      return item.isms == val6
    })
  }
  const sql2 = 'select * from lcollege';

  let data2: any = await queryAll(sql2)
  let min = (Number(pageIndex) - 1) * Number(page)
  let max = Number(pageIndex) * Number(page)

  let brr = data.slice(min, max)
  ctx.body = {
    code: "01",
    msg: "h获取成功",
    data,
    data2,
    brr,
  };
};
export const getcollegelist = async (ctx: any) => {
  const sql = "select * from lcollege";
  let data: any = await queryAll(sql);
  ctx.body = {
    code: "01",
    msg: "获取成功",
    data,
  };
};
export const addstudent = async (ctx: any) => {
  const sql = 'select * from scb';
  let { name, scb, xsphone, cid, jzphone, stage, totlemoney, nowmoney, qwstage, sex, msscore, image, imgtype } = ctx.request.query

  let imgCode = Buffer.from(image, "base64");
  let lastname = imgtype.slice(imgtype.indexOf("/") + 1);
  let imgName = `${v1().split("-").join("")}.${lastname}`;
  let src = path.join(__dirname, "../../public/file", imgName);
  fs.writeFileSync(src, imgCode);

  let url=`http://localhost:4000/public/file/${imgName}`
  
  let data: any = await queryAll(sql)
  const sql2 = 'select * from studentdata';
  let data2: any = await queryAll(sql2)
  let id = new Date().getTime()
  let isms = Number(msscore) >= 70
  await queryAll(`insert into studentdata (id,number,name,cid,xsphone,college,stage,course,class,stop) values('${id}','${id}','${name}','${cid}','${xsphone}','${qwstage}','${stage}','${stage}','null','正常')`)

  await queryAll(`insert into scb (id,name,scb,xsphone,cid,jzphone,stage,totlemoney,nowmoney,qwstage,sex,msscore,course,class,jfqk,isms,image,banji,shuse) values('${id}','${name}','${scb}','${xsphone}','${cid}','${jzphone}','${stage}','${totlemoney}','${nowmoney}','${qwstage}','${sex}','${msscore}','null','null','${nowmoney}/${totlemoney}','${isms}','${url}','null','null')`)
  ctx.body = {
    code: "01",
    msg: "添加成功",
    data,
    data2,
  }

}
export const getjwlist = async (ctx: any) => {
  const sql = "select * from scb";
  let data: any = await queryAll(sql);
  let data2 = data.map(async (item: any) => {
    item.course = null;
    item.class = null;
    item.jfqk = item.nowmoney + "/" + item.totlemoney;
    return item;
    //
  });
  ctx.body = {
    code: "01",
    msg: "获取成功",
    data2,
  };
};
export const getkclist = async (ctx: any) => {
  let { val } = ctx.request.query;

  const sql = "select * from lcollege";
  let data: any = await queryAll(sql);

  let list = data.find((item: any) => {
    return item.college == val;
  });

  ctx.body = {
    code: "01",
    msg: "获取成功",
    info: list,
  };
};
export const setclass = async (ctx: any) => {
  let { id, val,banji,shuse } = ctx.request.query
  
  const sql = 'select * from lcollege';
  let data: any = await queryAll(sql)
  await queryAll(`update studentdata set class='${val}' where number='${id}'`)
  await queryAll(`update scb set class='${val}',banji='${banji}',shuse='${shuse}' where id='${id}'`)

  ctx.body = {
    code: '01',
    msg: "获取成功",

  }

}

export const diststudent = async (ctx: any) => {
  let { id } = ctx.request.query
  const sql = 'select * from scb';
  let data: any = await queryAll(sql)

  await queryAll(`delete from scb where id=${id}`)

  ctx.body = {
    code: "01",
    msg: "获取成功",
    data,
  }

}
export const amendstudent = async (ctx: any) => {
  let { id, scb, name, xsphone, jzphone, cid, stage, totlemoney, nowmoney, qwstage, sex } = ctx.request.query
  console.log(id, scb, name, xsphone, jzphone, cid, stage, totlemoney, nowmoney, qwstage, sex);

  const sql = 'select * from scb';
  let data: any = await queryAll(sql)
  await queryAll(`update scb set scb='${scb}',name='${name}',xsphone='${xsphone}',jzphone='${jzphone}',cid='${cid}',stage='${stage}',totlemoney='${totlemoney}',nowmoney='${nowmoney}',qwstage='${qwstage}',sex='${sex}' where id='${id}'`)
  ctx.body = {
    code: '01',
    msg: "修改成功",
    data,
  }
};

export const setisms = async (ctx: any) => {
  let { id } = ctx.request.query
  console.log(id)

  const sql = 'select * from scb';
  let data: any = await queryAll(sql)
  let i = data.findIndex((item: any) => {
    return item.id == id
  })
  if (data[i].isms == 'true') {
    await queryAll(`update scb set isms='false' where id='${id}'`)
  } else {
    await queryAll(`update scb set isms='true' where id='${id}'`)
  }

  ctx.body = {
    code: '01',
    msg: "修改成功",
    data,
  }

}


export const upload = async (ctx: any) => {
    // koa-body 在处理完 file 后会绑定在 ctx.request.files
    const file = ctx.request.files.file;
    //[name,index,ext] - 分隔文件名
    const fileNameArr = file.name.split("."); //存放切片的目录
    const chunkDir = `${UPLOAD_DIR}/${fileNameArr[0]}`;
    if (!fse.existsSync(chunkDir)) {
      //没有目录就创建目录
      //创建大文件的临时目录
      await fse.mkdirs(chunkDir);
    } //原文件名.index - 每个分片的具体地址和名字
    const dPath = path.join(chunkDir, fileNameArr[1]); //将分片文件从temp中移动到本次上传大文件的临时目录
    await fse.move(file.path, dPath, {
      overwrite: true,
    });
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "切片上传成功",
    };
  };
  
  export const merge = async (ctx: any) => {
    const { name } = ctx.request.body;
    const fname = name.split(".")[0];
    const chunkDir = path.join(UPLOAD_DIR, fname);
    const chunks = await fse.readdir(chunkDir);
    chunks
      .sort((a: any, b: any) => a - b)
      .map((chunkPath: any) => {
        // 合并文件
        fse.appendFileSync(
          path.join(UPLOAD_DIR, name),
          fse.readFileSync(`${chunkDir}/${chunkPath}`)
        );
      }); // 删除临时文件夹
    fse.removeSync(chunkDir);
    let sql = `update version set logo='http://localhost:4000/upload/${name}'`;
    let result = await queryAll(sql);
    if (result) {
      ctx.status = 200; // 返回文件地址
      ctx.body = {
        msg: "合并成功",
        url: `http://localhost:4000/upload/${name}`,
      };
    }
  };


  //获取版本
export const getVersion = async (ctx: any) => {
    let sql = `select * from version`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "获取版本信息",
      data: res,
    };
  };
  
  export const editVersionTitle = async (ctx: any) => {
    const { title } = ctx.request.body;
    let sql = `update version set title='${title}'`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "修改标题成功",
      data: res,
    };
  };
  
  //修改登录账号
  
  export const editVersionLoginRoot = async (ctx: any) => {
    const { login_root } = ctx.request.body;
    let sql = `update version set login_root='${login_root}'`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "修改登录账号成功",
      data: res,
    };
  };


  //修改企业名称

export const editVersionCompanyName = async (ctx: any) => {
    const { company_name } = ctx.request.body;
    let sql = `update version set company_name='${company_name}'`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "修改企业名称成功",
      data: res,
    };
  };
  
  //修改教学周期函数
  export const editVersionDuration = async (ctx: any) => {
    const { duration } = ctx.request.body;
    let sql = `update version set duration='${duration}'`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "修改教学周期时长成功",
      data: res,
    };
  };



// 获取员工表
export const getEmployeeList = async (ctx: any) => {
    let sql = `select * from employee`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "获取员工表",
      data: res,
    };
  };
  
  export const addEmployeeList = async (ctx: any) => {
    const {
      number,
      name,
      sex,
      age,
      userRoot,
      phone,
      email,
      college,
      campus,
      stage,
      position,
    } = ctx.request.body;
    let sql = `insert into employee(number,name,sex,age,userRoot,phone,email,college,campus,stage,position) values('${number}','${name}','${sex}','${age}','${userRoot}','${phone}','${email}','${college}','${campus}','${stage}','${position}')`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "获取员工表",
      data: res,
    };
  };



  //导入数据
export const importEmployeeDate = (ctx: any) => {
    const { importDate } = ctx.request.body;
    importDate.forEach(async (item: any) => {
      await queryAll(
        `insert into employee(number,name,sex,age,identity,userRoot,phone,email,college,campus,stage,position,state,remark) values('${item.number}','${item.name}','${item.sex}','${item.age}','${item.identity}','${item.userRoot}','${item.phone}','${item.email}','${item.college}','${item.campus}','${item.stage}','${item.position}','${item.state}','${item.remark}')`
      );
    });
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "导入成功",
      data: [],
    };
  };
  
  //修改员工信息
  
  export const editEmployeeInfo = async (ctx: any) => {
    const { editObj } = ctx.request.body;
    let sql = `update employee set name='${editObj.name}',sex='${editObj.sex}',age='${editObj.age}', identity='${editObj.identity}' ,userRoot='${editObj.userRoot}',phone='${editObj.phone}',email='${editObj.email}',college='${editObj.college}',campus='${editObj.campus}',stage='${editObj.stage}',position='${editObj.position}',state='${editObj.state}',remark='${editObj.remark}' where id = ${editObj.id}`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "修改成功",
      data: res,
    };
  };
  
  //删除员工信息
  
  export const DelEmployee = async (ctx: any) => {
    const { delObj } = ctx.request.body;
    let sql = `delete from employee where id = ${delObj.id}`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "删除成功",
      data: res,
    };
  };



  //获取角色列表
export const getRoleList = async (ctx: any) => {
    let sql = `select * from role`;
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "删除成功",
      data: res,
    };
  };
  
  //添加角色
  export const addRoleList = async (ctx: any) => {
    const { role, explain, child_admin, privilege } = ctx.request.body;
    let sql = `insert into role(role, role_explain, child_admin, privilege) values('${ role }', '${ explain }', '${ JSON.stringify(child_admin) }', '${ JSON.stringify(privilege) }');`;
    console.log(sql);
    
    let res = await queryAll(sql);
    ctx.status = 200;
    ctx.body = {
      code: "200",
      msg: "删除成功",
      data: res,
    };
  };
  





